Ext.namespace("DSYGrid.component");
/**
 * 创建DSYWidget管理器
 */
if (!window.DSYWidget) {
    window.DSYWidget = {
        Manager: {
            grid: {}
        }
    };
} else if (!window.DSYWidget.Manager) {
    window.DSYWidget.Manager = {
        grid: {}
    };
} else if (!window.DSYWidget.Manager.grid) {
    window.DSYWidget.Manager.grid = {};
}
var isMultiHeader=false;
/**
 * 创建表格封装对象
 *
 * @returns {DSYGrid}
 */
function DSYGridV2() {
    //创建配置对象，存储各种基本属性
    this.config = {
        /*itemId: null,// gridid，可根据该id获取配置信息
         renderTo: null,// 渲染Grid的容器
         title: null,// 标题
         width: null,// 宽度
         height: null,// 高度
         rowCss: null,//行样式css
         store: null,//grid数据源，最高优先级
         data: null,//Grid数据集,次级优先级
         dataUrl: null,// Grid数据源地址，最低优先级
         tbar: [],//顶部工具栏
         bbar: [],//底部工具栏
         rbar: [],//右侧工具栏
         */
        itemId: 'DSY',
        grid: null,//存储创建的表格
        autoLoad: true,//是否立即加载，默认立即加载
        columns: [],// 列模型
        columnLines: true,// 表格线
        fields: [],// 解析数据的字段
        border: true,//是否显示边界，默认true显示
        checkBox: false,// 是否显示复选框，默认不显示
        cellTip: true,//是否显示单元格提示，默认提示
        selModel: {
            selType: 'rowmodel',//选择模式，主要有cellmodel/rowmodel/checkboxmodel
            mode: "SINGLE"     //s是否多选，默认多选,"SINGLE"/"SIMPLE"/"MULTI"
            //checkOnly:true,选择模式为checkboxmodel时，默认false，为true时只有点击复选框才选中行
        },
        filterStauts: false, // 配置是否启动合并行
        remoteSort: false,//排序方式：是否远程后端排序，默认前端排序
        // 上下左右工具栏配置,可配置height、padding、margin等
        tbarConfig: {
            height: 35,
            padding: '0 10 0 10'
        },
        bbarConfig: {},
        lbarConfig: {},
        rbarConfig: {},
        plugins: [],//插件
        features: [],//统计插件
        params: {},//发送ajax请求数据源时传递的参数
        lineConfig:{
        	//width:"1",
        	//color:"#C0C0C0"
        },//定义边框样式
        //表头相关配置
        headerConfig: {
            headerJson: [],        // 表头json数组
            headerUrl: null,         // 表头配置源
            columnAutoWidth: true,  // 列宽自适应，默认自适应
            headerCss: 'background-color: #eef6fb;color: #000;text-align: center;font-weight: normal !important;font-family: SimHei !important;',// 表头默认样式
            headerCssOver: 'background-color: #eef6fb;color: #6AB5EE;',// 表头默认样式：鼠标悬浮
            columnCls: 'nowrap' // 配置是否换行，nowrap不换行，normal换行
        },
        //分页相关配置
        pageConfig: {
            enablePage: true,// 是否分页，默认分页
            pageSize: 20,// 每页显示数据数
            pageNum: false,//是否显示每页条数
            pageNumStyle: 'combo',//显示样式combo/numberfield
            pageNumWidth: 60,//每页显示记录数宽度
            pageNumIndex: 0,//每页条数显示位置
            pageToolBar: null,//分页按钮,表格创建后放置分页按钮
            refreshBtn: false//默认不显示刷新按钮
        },
        isLocalStorage: true,// 是否本地存储，默认存储
        enableColumnHide:false,//表格下拉列表列隐藏列是否显示，默认不显示
        enableLocking:true,//表格下拉列表列锁定列是否显示，默认显示
        rownumbererResize:false,//表格rownumber列是否自适应列宽，默认不自适应
        listeners: {
            beforeitemclick: function (self, record, item, index, e) {//表格点击事件添加锁定列处理
            	if(self.ownerGrid.enableLocking){
            		var lockedGrid = self.ownerGrid.lockedGrid;
            		var normalGrid = self.ownerGrid.normalGrid;
            		var lockedNode =  lockedGrid.getView().getNodes(index)[0];
                    var normalNode =  normalGrid.getView().getNodes(index)[0];
            		//表格点击行变色
                    $(lockedGrid.el.dom).find('table.x-grid-item-click').removeClass('x-grid-item-click');
                    $(normalGrid.el.dom).find('table.x-grid-item-click').removeClass('x-grid-item-click');
                    $(lockedNode).addClass('x-grid-item-click');
                    $(normalNode).addClass('x-grid-item-click');
            	}else{
            		//表格点击行变色
                    $(self.el.dom).find('table.x-grid-item-click').removeClass('x-grid-item-click');
                    $(item).addClass('x-grid-item-click');
            	}
            },
            columnresize:function(ct,column,width,e){//列宽拖动事件
            	if(ct.grid.ownerGrid.enableLocking){
            		var saveColumns = new Array();
                	if(ct.grid.ownerGrid.isLocalStorage && DSYGrid.getLocalStorageFlag(ct.grid.ownerGrid.columns)){
                		var lockedColumns = ct.grid.ownerGrid.lockedGrid.getColumns();
                		var normalColumns = ct.grid.ownerGrid.normalGrid.getColumns();
                		var saveItemId = ct.grid.ownerGrid.itemId;
                		for(var i in lockedColumns){
                			saveColumns.push(lockedColumns[i]);
                		}
                		for(var i in normalColumns){
                			normalColumns[i].locked = false;
                			saveColumns.push(normalColumns[i]);
                		}
                		DSYGrid.localStorageByColumns(saveColumns,saveItemId);
                	}
            	}else{
            		if(ct.grid.isLocalStorage &&  DSYGrid.getLocalStorageFlag(ct.grid.getColumns())){
            			DSYGrid.localStorage(ct.grid);
            		}
            	}
            },
            columnmove:function( ct , column , fromIdx , toIdx , e ){//列变更拖动事件
            	if(ct.grid.ownerGrid.enableLocking){
            		var saveColumns = new Array();
                	if(ct.grid.ownerGrid.isLocalStorage && DSYGrid.getLocalStorageFlag(ct.grid.ownerGrid.columns)){
                		var lockedColumns = ct.grid.ownerGrid.lockedGrid.getColumns();
                		var normalColumns = ct.grid.ownerGrid.normalGrid.getColumns();
                		var saveItemId = ct.grid.ownerGrid.itemId;
                		for(var i in lockedColumns){
                			saveColumns.push(lockedColumns[i]);
                		}
                		for(var i in normalColumns){
                			normalColumns[i].locked = false;
                			saveColumns.push(normalColumns[i]);
                		}
                		DSYGrid.localStorageByColumns(saveColumns,saveItemId);
                	}
            	}else{
            		if(ct.grid.isLocalStorage &&  DSYGrid.getLocalStorageFlag(ct.grid.getColumns())){
            			DSYGrid.localStorage(ct.grid);
            		}
            	}
            },
            lockcolumn: function ( ct , column , e ){//列锁定事件
            	if(ct.enableLocking){
            		var saveColumns = new Array();
                	if(ct.isLocalStorage && DSYGrid.getLocalStorageFlag(ct.columns)){
                		var lockedColumns = ct.lockedGrid.getColumns();
                		var normalColumns = ct.normalGrid.getColumns();
                		var saveItemId = ct.itemId;
                		for(var i in lockedColumns){
                			saveColumns.push(lockedColumns[i]);
                		}
                		for(var i in normalColumns){
                			normalColumns[i].locked = false;
                			saveColumns.push(normalColumns[i]);
                		}
                		DSYGrid.localStorageByColumns(saveColumns,saveItemId);
                	}
            	}
            },
            unlockcolumn: function ( ct , column , e ){//列解除锁定事件
            	if(ct.enableLocking){
            		var saveColumns = new Array();
                	if(ct.isLocalStorage && DSYGrid.getLocalStorageFlag(ct.columns)){
                		var lockedColumns = ct.lockedGrid.getColumns();
                		var normalColumns = ct.normalGrid.getColumns();
                		var saveItemId = ct.itemId;
                		for(var i in lockedColumns){
                			saveColumns.push(lockedColumns[i]);
                		}
                		for(var i in normalColumns){
                			normalColumns[i].locked = false;
                			saveColumns.push(normalColumns[i]);
                		}
                		DSYGrid.localStorageByColumns(saveColumns,saveItemId);
                	}
            	}
            }
        },
        //导出功能配置
        exportExcel: {
            exportExcel: false,//是否导出，默认false，不导出
            url: null,//导出按钮URL
            param: {},//导出参数
            btn: null,//自定义导出按钮，默认为null
            //给导出按钮绑定事件
            listeners: {}
        },
        insertData: function (index, records) {
        	if(records){
        		var gird_insert = this;
                var store = gird_insert.getStore();
                var view = gird_insert.getView();
                if (typeof index == 'undefined' || index == null) {
                    if (this.getSelectionModel().getSelection().length > 0) {
                        var selectedGrid = this.getSelectionModel().getSelection();
                        index = this.getStore().indexOf(selectedGrid[selectedGrid.length - 1]) + 1;
                    } else {
                        index = store.getCount();
                    }
                }
                //如果存在编辑插件，取消编辑
                for (var i = 0; i < gird_insert.getPlugins().length; i++) {
                    if (gird_insert.getPlugins()[i].ptype == 'cellediting' || gird_insert.getPlugins()[i].ptype == 'rowediting') {
                        gird_insert.getPlugins()[i].completeEdit();
                    }
                }
                store.insertData(index, records);
                view.refresh();
                if (view.getRow(0) != null) {
                    //滚动到指定行
                	var lockedGrid = null;
                    var normalGrid = null;
                    var lockedView = null;
                    var normalView = null;
                    if(gird_insert.enableLocking){
                    	var lockedGrid = gird_insert.lockedGrid,
                		normalGrid = gird_insert.normalGrid,
                		lockedView = lockedGrid.getView(),
                		normalView = normalGrid.getView();
                    	lockedView.scrollTo(0, view.getRow(0).clientHeight * index);
                    	normalView.scrollTo(0, view.getRow(0).clientHeight * index);
                    }else{
                    	view.scrollTo(0, view.getRow(0).clientHeight * index);
                    }
                }
        	}
        },
        getCurrentRecord: function () {
            var grid = this;
            var item = $(grid.el.dom).find('table.x-grid-item-click');
            if (item.length <= 0) {
                return null;
            }
            var recordIndex = $(item[0]).attr('data-recordindex');
            var record = grid.getStore().getAt(recordIndex);
            record.recordIndex = parseInt(recordIndex);
            return record;
        }
    };
    /**
     * 递归数组：获取列解析模型field
     * @param array 表头配置数组
     */
    this.setGridFields = function (array) {
        //如果为空返回
        if (array == null || array.length <= 0) {
            return;
        }
        for (var array_seq in array) {
            if (array[array_seq].dataIndex && array[array_seq].dataIndex != '') {
                var field = $.extend({}, {
                    name: array[array_seq].dataIndex,// 设置列数据字段
                    type: array[array_seq].type == null ? "auto" : array[array_seq].type // 设置列解析类型
                }, array[array_seq]);
                this.config.fields.push(field);
            }
            if (array[array_seq].columns && Ext.isArray(array[array_seq].columns)) {
                this.setGridFields(array[array_seq].columns);
            }
        }
    };
    /**
     * 根据配置数组单列，生成对应的单列配置
     * @param col
     * @returns {*}
     */
    this.setGridColumn = function (col) {
        var column = (col);
        if (col.text) {
            column.header = col.text;// 设置标题文字
            //设置必选标志
            if (col.headerMark && col.headerMark == 'star') {
                column.header = '<span class="required">✶</span>' + column.header;
            }
            delete column.text;
        }
        column.hidden = col.hidden ? col.hidden : false;// 设置列隐藏
          //isOnTitleElDblClick设置为true，双击表头可以调整宽度，不设置，双击表头不可以调整宽度
          column.isOnTitleElDblClick=column.isOnTitleElDblClick||false;
        //设置宽度默认值
        if (typeof (col.width) == 'undefined' || col.width == null) {
            col.width = 100;
        }
        //判断列为自适应还是固定宽度
        if (this.config.headerConfig.columnAutoWidth) {
            //解决表格重置表头列设置太窄，图片被遮挡的问题
          if(col.xtype == "rownumberer"){
              column.width = col.width&&col.width>45 ? col.width : 45;
          }else{
              column.flex = col.width ? col.width : 100;// 设置列比例;
              delete column.width;
          }
      } else {
          //解决表格重置表头列设置太窄，图片被遮挡的问题
          if(col.xtype == "rownumberer"){
              column.width = col.width&&col.width>45 ? col.width : 45;
          }else{
              column.width = col.width ? col.width : 100;// 设置固定列宽;
          }

      }
        // 默认列渲染类型为字符型
        // 设置列渲染类型为数字型，右对齐
        if (col.type == "int") {
            column.align = "right";
            column.xtype = "numbercolumn";
            column.format = "0";
        } else if (col.type == "float") {
            column.align = "right";
            column.xtype = "numbercolumn";
        }
        if (col.xtype != null) {
            column.xtype = col.xtype;
            //表格配置本地存储并且是序号列的时候添加重置本地记忆按钮
            if(this.config.isLocalStorage){
            	if(col.xtype == "rownumberer"){
            		column.align = "center";
            		column.dataIndex="rownumberer";
            		var menu = DSYGrid.getMenu();
                	column.header = '<a href = "#" onclick ="DSYGrid.localStorageRemove(\''+menu+'\',\''+this.config.itemId+'\')"><img src="/report/image/sysbutton/chongzhi.png" width="16px" height="16px" title="点击重置表头" /></a>';
                }
            }
        }
        //设置列对齐方式
        if (col.align != null && col.align != "") {
            column.align = col.align;
        }
        // 设置列渲染格式化
        if (col.format != null && col.format != "") {
            column.format = col.format;
        }
        // 设置列是否必选与设置是否提示
        if (col.css || col.tipable) {
            column.renderer = (function () {
                var colObj = col;
                return function (data, cell) {
                    if (colObj.tipable) {
                        //设置单元格内容提示
                        cell.tdAttr = 'data-qtip="' + data + '"';
                    }
                    if (colObj.css) {
                        return '<span style="' + css + '">' + data + '</span>';
                    }
                    return data;
                };
            })();
        }
        return column;
    };
    /**
     * 递归数组：获取列渲染模型columns
     * @param array 表头配置数组
     */
    this.setGridColumns = function (array) {
        //如果为空返回
        if (array == null || array.length <= 0) {
            return;
        }
        var columns = [];
        //防止表格控件因为for in 的方式出现空白列故 修改为正常for循环
        for (var i = 0; i < array.length; i++) {
            var column = {};
            column = this.setGridColumn(array[i]);
            if (array[i].columns && Ext.isArray(array[i].columns)) {
                column.columns = this.setGridColumns(array[i].columns);
            }
            columns.push(column);
        }
        return columns;
    };
    /**
     * 配置表格,初始化
     */
    this.loadProperty = function () {
        var itemId = this.config.itemId;
        var headerJson = this.config.headerConfig.headerJson;
        var headerURL = this.config.headerConfig.headerUrl;
        var isLocalStorage = this.config.isLocalStorage;
        /*
         // 设置表头样式和表头悬浮样式
         if (this.config.headerConfig.headerCss == null) {
         this.config.headerConfig.headerCss = "background-color: #6AB5EE;color: #fff;text-align: center;";
         } else {
         this.config.headerConfig.headerCss = "background-color: #6AB5EE;color: #fff;text-align: center;" + this.config.headerConfig.headerCss;
         }
         $('<style>.x-column-header-inner{' + this.config.headerConfig.headerCss + '}</style>').appendTo(document.body);
         if (this.config.headerConfig.headerCssOver == null) {
         this.config.headerConfig.headerCssOver = "background-color: #eef6fb;color: #6AB5EE;";
         } else {
         this.config.headerConfig.headerCssOver = "background-color: #eef6fb;color: #6AB5EE;" + this.config.headerConfig.headerCssOver;
         }
         $('<style>.x-column-header-over{' + this.config.headerConfig.headerCssOver + '}</style>').appendTo(document.body);
         */
        // 将表格列配置转换为JSON
        var v_colArray = null;// 表头JSON数组
        if (headerJson != null && headerJson.length > 0 && headerURL != "" && headerURL != {}) {
            v_colArray = headerJson;
        } else if (headerURL != null && headerURL != "") {
            // 如果表头配置源不为空，就Ajax请求获取配置源
            Ext.Ajax.request({
                method: 'POST',
                url: this.config.headerConfig.headerUrl,
                params: {
                    itemId: itemId
                },
                async: false,
                success: function (response) {
                    // 获取返回的JSON，并根据itemId，获取表头配置信息
                    var respText = Ext.util.JSON.decode(response.responseText);
                    v_colArray = eval(respText.header);
                },
                failure: function () {
                    Ext.MessageBox.minWidth = 120;
                    Ext.Msg.alert('提示', '获取表格列配置信息失败！')
                }
            });
            this.config.headerConfig.headerJson = v_colArray;
        }
        // 将表格列配置转换为columns和fields
        if (v_colArray != null) {
            //循环配置数组，生成fields
            this.setGridFields(v_colArray);
            //循环配置数组，生成columns
            var serverHeaderColumn = this.setGridColumns(v_colArray);
            //克隆headJson获取新的数字，使得headJson和实际操作数组解耦
            var headerColumns = Ext.clone(serverHeaderColumn);
        	if(isLocalStorage && DSYGrid.getLocalStorageFlag(headerColumns)){
        		var menu = DSYGrid.getMenu();
        		//当选择本地存储时从本地获取存储信息
        		var localColumns = [];
             	if(window.localStorage){
                    var storage = window.localStorage;
                    //storage.clear();
                    var jsonstr = storage.getItem(menu+itemId);
                    if(jsonstr){
                   	   localColumns =JSON.parse(jsonstr) ;
                    }
               }
             	//当存在本地存储时执行本地存储，否则执行服务的存储的列信息
        		if(localColumns != null && localColumns.length > 0){
                    isMultiHeader=false;
                    var processedColumns = loopColumn(headerColumns,localColumns)
                    // 多行表头执行递归获取宽度，单行表头执行之前的代码逻辑
                    if(isMultiHeader){
                        this.config.columns = processedColumns;
                    }else{
                        // headerColumns  localColumns
                        var newList = new Array();//服务端新增列
                        var pre="00";
                        var lastList = new Array();//表格最终执行列
                        var serverlExists = true;
                        //循环服务端和本地存储的列信息，判断列是否有新增或者删除
                        for(var i=0;i<headerColumns.length;i++){
                            var exist=false;
                            for(var j=0;j<localColumns.length;j++){
                                if(headerColumns[i].dataIndex == localColumns[j].dataIndex){
                                    exist=true;
                                    pre=headerColumns[i].dataIndex;
                                    headerColumns[i].width = localColumns[j].width;
                                    if(localColumns[j].locked){
                                        headerColumns[i].locked = localColumns[j].locked;
                                    }
                                    if(localColumns[j].hidden){
                                        headerColumns[i].hidden = localColumns[j].hidden;
                                    }
                                    localColumns[j] = headerColumns[i];
                                }
                            }
                            //当服务端的列有不存在的则标识服务端和本地有变更
                            if(!exist){
                                serverlExists=false;
                                //当标识为00是则表示列新增到开头直接把列添加到最终存储中
                                if(pre == "00"){
                                    lastList.push(headerColumns[i]);
                                }else{
                                    //记录新增列的父级
                                    headerColumns[i].dataIndex = pre+"#"+headerColumns[i].dataIndex;
                                    newList.push(headerColumns[i]);
                                }
                            }
                        }
                        //当列无信息或者删除是直接执行本地存储
                        if (serverlExists && localColumns.length == headerColumns.length) {
                            this.config.columns = localColumns;
                        } else {
                            var localList = new Array();
                            //遍历本地存储和服务端存储 删除本地存储在服务端存储中不存在的部分
                            for (var i = 0; i < localColumns.length; i++) {
                                var exist = false;
                                for (var j = 0; j < headerColumns.length; j++) {
                                    if (localColumns[i].dataIndex == headerColumns[j].dataIndex) {
                                        exist = true;
                                    }
                                }
                                if (exist) {
                                    localList.push(localColumns[i]);
                                }
                            }
                            //遍历本地存储和新增列根据本地存储顺序和新增列父子关系把得到的结果存储到最终列中
                            for (var i = 0; i < localList.length; i++) {
                                lastList.push(localList[i]);
                                for (var j = 0; j < newList.length; j++) {
                                    var str = newList[j].dataIndex.split("#");
                                    if (str[0] == localList[i].dataIndex) {
                                        newList[j].dataIndex = str[1];
                                        lastList.push(newList[j]);
                                    }
                                }
                            }
                            this.config.columns = lastList;
                            //刷新本地存储
                            DSYGrid.localStorageByColumns(lastList,itemId);
                        }
                    }


            	}else{
            		this.config.columns = headerColumns;
            	}
        	}else{
        		this.config.columns = headerColumns;
        	}
        	
        }
    };
    //循环处理表头数据和本地记忆的数据
    function loopColumn(columns,localColumns){
        var processedColumns = []; // 用于存储处理后的列数据
        for (var i = 0; i < columns.length; i++) {
            var column = Ext.clone(columns[i]); // 克隆当前列对象，避免直接修改原始列数据
            for (var j = 0; j < localColumns.length; j++) {
                if ((column.dataIndex&&column.dataIndex == localColumns[j].dataIndex&&localColumns[j].dataIndex)||(!column.dataIndex&&column.header==localColumns[j].header&&!localColumns[i].dataIndex)) {
                    column.width = localColumns[j].width;
                    if (localColumns[j].locked) {
                        column.locked = localColumns[j].locked;
                    }
                    if (localColumns[j].hidden) {
                        column.hidden = localColumns[j].hidden;
                    }
                    localColumns[j]
                }
            }

            if (column.columns && column.columns.length > 0) {
                isMultiHeader=true;
                column.columns = loopColumn(column.columns,localColumns); // 递归处理子列数据
            }

            processedColumns.push(column); // 将处理后的列数据添加到结果数组中
        }
        return processedColumns;
    }
    /**
     * 创建grid
     */
    this.create = function (config) {
    	// 兼容IE8不支持Array.isArray方法
    	if (!Array.isArray) {
    		// 添加isArray原型方法
    		Array.isArray = function(arg) {
    			return Object.prototype.toString.call(arg) === '[object Array]';
    		};
    	}
    	// 判断是否已经配置了额外样式，如果已经配置了额外样式，则使用数组方式
    	if(config && config.cls) {
    		// 样式数组
    		var clsArr = [];
    		// 判断传递过来cls是否是数组
    		if(Array.isArray(config.cls)) {
    			clsArr = config.cls;
    		}else {
    			clsArr.push(config.cls);    			
    		}
    		// 判断配置，如果配置headerConfig中columnCls为normal则换行，否则不换行
    		if(config.headerConfig && config.headerConfig.columnCls == "normal") {
    			clsArr.push("x-column-header-text-normal");
    		}else {
    			clsArr.push("x-column-header-text-nowrap");
    		}
    		config.cls = clsArr;
    	// 判断是否配置normal
    	}else if (config && config.headerConfig && config.headerConfig.columnCls == "normal") {
    		config.cls = "x-column-header-text-normal";
    	// 没有任何配置的情况下默认不换行
    	}else {
    		config.cls = "x-column-header-text-nowrap";
    	}
        // 开启动态加载
        Ext.Loader.setConfig({
            enabled: true
        });
        // 设置扩展插件路径
        //Ext.Loader.setPath('Ext.ux','js/ext5.1/ux');
        Ext.require([
            'Ext.grid.*',
            'Ext.data.*',
            'Ext.util.*',
            'Ext.tip.QuickTipManager',
            'Ext.PagingToolbar'
        ]);
        //读取标签中的ext:qtip属性，并为它赋予显示提示的动作
        Ext.QuickTips.init();
        Ext.tip.QuickTipManager.init();
        // 配置合并单元格
        $.extend(true, this.config, config);
        var itemId = this.config.itemId;
        var filterConfig = null;
        var storeHeader = {};
        var storeHeaderCount = 0;
        var storeJson = config.headerConfig.headerJson;
        // 判断是否启用合并行
        if(config.filterStauts) {
	        // 判断是否有多选框，如果有多选框则当前列数加1
	        if(config.checkBox) {
	        	storeHeaderCount++;
	        }
	        // 计算列数以及记录有哪些字段
	        for(var i = 0; i < storeJson.length; i++) {
	        	if(storeJson[i].hidden != true) {
	        		if(storeJson[i].filter == true) {
	        			if(!filterConfig) {
	        				filterConfig = [];
	        			}
	        			filterConfig.push(storeJson[i].dataIndex);
	        		}
	        		storeHeader[storeJson[i].dataIndex] = storeHeaderCount++;
	        	}
	        }
        }
        // 设置grid配置项
        this.loadProperty();
        // 创建store数据集
        var store = null;
        if (this.config.store) {
            store = this.config.store;
        } else if (this.config.data) {
            store = Ext.create('Ext.data.Store', {
                fields: this.config.fields,
                pageSize: this.config.pageConfig.enablePage ? this.config.pageConfig.pageSize : 0,
                data: this.config.data
            });
        } else if (this.config.dataUrl) {
            store = Ext.create('Ext.data.Store', {
                fields: this.config.fields,
                pageSize: this.config.pageConfig.enablePage ? this.config.pageConfig.pageSize : 0,
                remoteSort: this.config.remoteSort,// 后端进行排序
                proxy: {// ajax获取后端数据
                    type: "ajax",
                    //method: "POST",
                    actionMethods : {
    					read : 'POST' // Store设置请求的方法，与Ajax请求有区别
    				},
                    url: this.config.dataUrl,
                    timeout:  600000,
                    reader: {
                        type: "json",
                        root: "list",
                        totalProperty: "totalcount"
                    },
                    simpleSortMode: true
                }
            });
        }
        // 设置参数
        if (store != null) {
            store.getProxy().extraParams = this.config.params;
            // 判断是否启用合并行
            if(config.filterStauts) {
            	// 添加过滤将与上一行数据相同的置为空
            	store.addFilter(function(items){
            		if(Array.isArray(filterConfig)){
            			var record = items.data;
            			// 记录合并行信息
            			if(!window._lastRecord) {
            				window._lastRecord = {};
            				// 记录当前行号
            				window._lastRecord.rowCount = 0;
            				// 记录需要合并的单元格
            				//window._lastRecord.megronRow = [];
            				window._lastRecord.megronRows = [];
            			}else {
            				window._lastRecord.rowCount++;
            			}
            			if(!!window._lastRecord.data) {
            				var nextTempValue = 0;
            				for(var i = 0; i < filterConfig.length; i++) {
            					if(record[filterConfig[i]] === window._lastRecord.data[filterConfig[i]]) {
            						var index = storeHeader[filterConfig[i]];
            						/*var index = (window._lastRecord.rowCount-1) * storeHeaderCount + storeHeader["ADNAME"];
	                				if(!!window._lastRecord.megronRow[window._lastRecord.megronRow.length - 1].rowSpan) {
	                					window._lastRecord.megronRow[window._lastRecord.megronRow.length - 1].rowSpan++;
	                				}else {
	                					window._lastRecord.megronRow[window._lastRecord.megronRow.length - 1] = {
                    						"index": index,
                    						"rowSpan": 2
	                    				};
	                				}*/
            						window._lastRecord.megronRows.push((window._lastRecord.rowCount-1) * storeHeaderCount + index);
            						if(nextTempValue === 0) {
            							//配置合并例外--第一行不合并
            							if(window._lastRecord.rowCount != 0){
            								items.data[filterConfig[i]] = "";
            							}
            						}
            						nextTempValue = 0;
            					}else {
            						//window._lastRecord.megronRow.push({});
            						// 记录前一条数据
            						window._lastRecord.data[filterConfig[i]] = record[filterConfig[i]];
            						nextTempValue = 1;
            					}
            				}
            			}else {
            				//window._lastRecord.megronRow.push({});
            				// 记录前一条数据
            				window._lastRecord.data = {};
            				for(var i = 0; i < filterConfig.length; i++) {
            					window._lastRecord.data[filterConfig[i]] = record[filterConfig[i]];                    				
            				}
            			}
            			return items;
            		}
            		return items;
            	});
            	store.on("load", function(){
            		/*for(var i = 0; i < window._lastRecord.megronRow.length; i++) {
	    			$($("div#grid-1043 td.x-grid-cell")[window._lastRecord.megronRow[i].index])[0].rowspan = 5;
	    			$($("div#grid-1043 td.x-grid-cell")[window._lastRecord.megronRow[i].index]).attr("rowspan", window._lastRecord.megronRow[i].rowSpan);
		    		}*/
            		if(Array.isArray(filterConfig) && window._lastRecord){
            			for(var i = 0; i < window._lastRecord.megronRows.length; i++){
            				if($($("#" + DSYGrid.getGrid(itemId).id + " td.x-grid-cell")[window._lastRecord.megronRows[i]])[0]){
            					$($("#" + DSYGrid.getGrid(itemId).id + " td.x-grid-cell")[window._lastRecord.megronRows[i]])[0].style.borderBottom = "none";            					
            				}
            				//$($("#" + DSYGrid.getGrid(itemId).id + " td.x-grid-cell")[window._lastRecord.megronRows[i]])[0].style.backgroundColor = "white";
            			}
            		}
            		/*var grid = DSYGrid.getGrid(itemId);
		    		var gridView = document.getElementById(grid.getView().id);
		    		var body = gridView.childNodes;
		    		var trArray = gridView.getElementsByTagName('tr');
		    		var lastTr = trArray[0];
		    		lastTr.childNodes[3].setAttribute('rowspan', 3);
		    		lastTr.childNodes[3].style['vertical-align'] = 'middle';*/
            		window._lastRecord = null;
            	});
            	// 数据改变后将合并单元格记录数据清空
            	store.on("datachanged", function(){
            		window._lastRecord = null;
            	});
            }
        }
        //创建导出按钮
        if (this.config.exportExcel.exportExcel) {
            var btn_export = Ext.create('Ext.Button', {
                width: 70,
                text: '导出',
                bindGrid: this.config.itemId,
                handler: function (btn) {
                    //给导出按钮绑定事件
                    DSYGrid.exportExcelClick(btn.bindGrid, {btn: btn});
                }
            });
            //设置导出按钮的id
            this.config.exportExcel.btn = btn_export;
            if (!this.config.tbar) {
                this.config.tbar = [];
            }
            this.config.tbar.push(btn_export);
        }
        //如果分页
        if (this.config.pageConfig.enablePage) {
            var pageConfig = this.config.pageConfig;
            //创建分页按钮
            this.config.pageConfig.pageToolBar = Ext.create("Ext.toolbar.Paging", {
                store: store,
                plugins: [new DSYGrid.component.PagingToolbar({pageConfig: pageConfig})],
                pageSize: pageConfig.pageSize,
                displayInfo: true,
                emptyMsg: "无结果 &nbsp;&nbsp;&nbsp;&nbsp; ",
                afterPageText: '页 共{0}页',
                beforePageText: '第',
                displayMsg: "共{2}条&nbsp;&nbsp;&nbsp;&nbsp;",
                firstText: '第一页',
                prevText: '前一页',
                nextText: '后一页',
                lastText: '最后一页',
                refreshText: '刷新',
                refreshBtn: pageConfig.refreshBtn,
                inputItemWidth:pageConfig.inputItemWidth,//分页控件页码框宽度 默认30
                border: false,
                listeners: {
                    afterrender: function (self) {
                        if (!self.refreshBtn) {
                            self.child('#refresh').hide();
                        }
                        //查询报表套表，修复翻页控件页数不正确显示问题
                        var afterTextItem = self.items.get("afterTextItem");
                        if(afterTextItem && self.getStore().totalCount){
                        	var pageCount = Math.ceil(self.getStore().totalCount/self.getStore().pageSize);
                        	afterTextItem.setText('页 共'+pageCount+'页');
                        }
                    },
                    change :function( self, pageData, eOpts ) {
                    	if(Ext.ComponentQuery.query('grid#' + itemId)[0].config.rownumbererResize){
                    		var column = Ext.ComponentQuery.query('grid#' + itemId)[0].columns[0];
                        	if(column){
                        		if(column.xtype == "rownumberer"){
                            		var pageCount = pageData.toRecord.toString();
                            		var rowWidth = pageCount.length * 10;
                            		var isLocalStorage = Ext.ComponentQuery.query('grid#' + itemId)[0].config.isLocalStorage;
                            		if(isLocalStorage){
                            			if(rowWidth < 45){
                                			rowWidth = 45;
                                		}
                            		}
                            		column.setWidth(rowWidth);
                            	}
                        	}
                    	}
                    }
                }
            });
            /*在工具栏添加分页按钮*/
            if (!this.config.tbar) {
                this.config.tbar = [];
            }
            this.config.tbar.push("->");
            this.config.tbar.push(this.config.pageConfig.pageToolBar);
        }
        //表格工具栏封装
        this.config.dockedItems = this.config.dockedItems ? this.config.dockedItems : [];
        if (this.config.tbar && this.config.tbar.length > 0) {
            var barConfig = $.extend({}, {
                xtype: 'toolbar',
                dock: 'top',
                items: this.config.tbar
            }, this.config.tbarConfig);
            this.config.dockedItems.push(barConfig);
            delete this.config.tbar;
        }
        if (this.config.rbar && this.config.rbar.length > 0) {
            var barConfig = $.extend({}, {
                xtype: 'toolbar',
                dock: 'right',
                items: this.config.rbar
            }, this.config.rbarConfig);
            this.config.dockedItems.push(barConfig);
            delete this.config.rbar;
        }
        if (this.config.lbar && this.config.lbar.length > 0) {
            var barConfig = $.extend({}, {
                xtype: 'toolbar',
                dock: 'bottom',
                items: this.config.lbar
            }, this.config.lbarConfig);
            this.config.dockedItems.push(barConfig);
            delete this.config.bbar;
        }
        if (this.config.bbar && this.config.bbar.length > 0) {
            var barConfig = $.extend({}, {
                xtype: 'toolbar',
                dock: 'bottom',
                items: this.config.bbar
            }, this.config.bbarConfig);
            this.config.dockedItems.push(barConfig);
            delete this.config.bbar;
        }
        if (this.config.dockedItems.length <= 0) {
            delete this.config.dockedItems;
        }
        if (this.config.rowCss != null) {
            $('<style>.' + this.config.itemId + '-DSYGrid-row {' + this.config.rowCss + '}</style>').appendTo(document.body);
        }
        //复选框选择模式
        if (this.config.checkBox) {
            var selModel = {
                selType: 'checkboxmodel',
                mode: 'SIMPLE'
            };
            this.config.selModel = $.extend({}, selModel, config.selModel);
            delete this.config.checkBox;
        }
        if(!DSYGrid.getLockFlag(this.config.columns)){
        	this.config.enableLocking = false;
        }
        this.config = $.extend(true, {
            selModel: this.config.selModel,
            enableKeyNav: true, //启用键盘导航
            store: store,
//            layout: 'border',//表格控件去除默认样式，如果应用此样式则锁定列无法实现
            viewConfig: {
                stripeRows: true,
                enableTextSelection: true,	//可以复制单元格文字
                columnsText: '显示的列',
                scrollOffset: 30,			// 表格右侧滚动条的宽度，默认是20px
                sortAscText: '升序',
                sortDescText: '降序',
                getRowClass: function (record, rowIndex, rowParams) {
                    return itemId + "-DSYGrid-row";
                }
            }
        }, this.config);
      //追加合计行样式,解决无数据时 ，合计行无下边问题
        if (this.config.features != null && this.config.features.length > 0) {
        	//当已经设置了组件位置时根据设置的来
        	if(!this.config.features[0].dock){
        		this.config.features[0].dock = "top";
        	}
        	$('<style>tr.x-grid-row-summary> td{border-bottom:1px solid;}</style>').appendTo(document.body);
        }
        
        if(this.config.lineConfig != null){
        	var color = this.config.lineConfig.color;
        	var width = this.config.lineConfig.width;
        	if(width == undefined){
        		width = 1;
        	}
        	if(color == undefined){
        		color == "C0C0C0";
        	}
        	$('<style>.x-grid-with-col-lines .x-grid-cell {border-bottom:'+width+'px solid '+color+';'+
        			'border-right:'+width+'px solid '+color+';}</style>').appendTo(document.body);
        }
        //如果锁定列则autoScroll为false
        if(this.config.enableLocking){
        	this.config.autoScroll = false;
        	this.config.scrollable = false;
        }
        this.config.grid = Ext.create('Ext.grid.Panel', this.config);
        // 判断是否启用合并行
        if(config.filterStauts) {
	        this.config.grid.addListener("reconfigure", function(self) {
	    		if(filterConfig) {
					filterConfig = null;
				}
	    		storeHeader = {};
	            storeHeaderCount = 0;
	    		var columns = self.getColumns();
	    		// 判断是否有多选框，如果有多选框则当前列数加1
		        if(self.config.checkBox) {
		        	storeHeaderCount++;
		        }
	    		for(var i = 0; i < columns.length; i++) {
	    			if(columns[i].config.hidden != true) {
	    				if(columns[i].config.filter == true) {
	    					if(!filterConfig) {
	    						filterConfig = [];
	    					}
	    					filterConfig.push(columns[i].config.dataIndex);
	    				}
	    				storeHeader[columns[i].config.dataIndex] = storeHeaderCount++;;
	    			}
	    		}
	        });
        }
        /*store.on("load", function(self){
        	var items = self.getData().items;
	        var headerJsons = config.headerConfig.headerJson;
	        var headerJson = [];
	        function getDumpContent(header) {
	        	if(!!header.columns && header.columns.length > 0) {
	        		for(var i = 0; i < header.columns.length; i++) {
	        			getDumpContent(header.columns[i])
	        		}
	        	}else {
	        		headerJson.push(header);
	        	}
	        }
	        for(var i = 0; i < headerJsons.length; i++) {
	        	getDumpContent(headerJsons[i]);
	        }
	        var gridDoms = $(DSYGrid.getGrid(itemId).el.dom).children();
	    	var tableDom = gridDoms[1];
	    	var childrenTables = $(tableDom).find("table");
	        for(var count = -1, i = 0; i < headerJson.length; i++) { // 遍历列
	        	!(headerJson[i].hidden == true) && count++;
	        	if(!!headerJson[i].rowspan) { // 判断列上是否设置有rowspan属性，值相同合并自动配置
	        		var recordData, rowCell, rowHeight, rowspan; // recordData记录上一个值；rowCell记录当前单元格；rowHeight记录当前单元格的高度；rowspan记录是否在进行合并行操作
	        		for(var j = 0; j < items.length; j++) { // 遍历数据集
	        			var dataValue = items[j].data[headerJson[i].dataIndex]; // 获取当前数据值
	        			// 判断当前数据值与上一个数据值是否相同
	        			if(!recordData || dataValue != recordData) {
	        				if(!!rowspan) { // 结束合并行
	        					rowCell.css("width", $(rowCell.parent()).css("width"))
	        					rowCell.css("position", "absolute"); // 设置为绝对定位
	        					rowCell.css("background-color", "#ffffff"); // 设置白色背景色
	        					rowCell.css("line-height", rowHeight + "px"); // 设置div高
	        					rowCell.css("padding", "0px 10px 0px 10px"); // 设置div内边距
	        					rowCell.css("border", "1px solid #c1c1c1"); // 设置边框
	        					rowCell.css("border-bottom-width", "0px"); // 设置边框
	        					rowCell.css("border-bottom-left", "0px"); // 设置边框
	        				}
	        				recordData = dataValue; // 更改数据集
	        				rowCell = $($($(childrenTables[j]).find("td")[count]).children()); // 更改单格
	        				rowHeight = parseInt($(childrenTables[j]).css("height").replace("px", "")); // 更改高度属性
	        				rowspan = false; // 退出合并状态
	        			}else {
	        				var nextRow = $($($(childrenTables[j]).find("td")[count]).children());
	        				rowHeight += parseInt($(childrenTables[j]).css("height").replace("px", "")); // 获取合并后的高度值
	        				nextRow.remove(); // 移除被合并的行
	        				if(j === (items.length - 1)) { // 最后一行默认结束
	        					rowCell.css("width", $(rowCell.parent()).css("width"))
	        					rowCell.css("position", "absolute"); // 设置为绝对定位
	        					rowCell.css("background-color", "#ffffff"); // 设置白色背景色
	        					rowCell.css("line-height", rowHeight + "px"); // 设置div高
	        					rowCell.css("padding", "0px 10px 0px 10px"); // 设置div内边距
	        					rowCell.css("border", "1px solid #c1c1c1"); // 设置边框
	        				}else {
	        					rowspan = true; // 设置当前状态正在进行合并行
	        				}
	        			}
	        		}
	        	}
	        }
        });*/
        //将本DSYGrid放入管理器
        window.DSYWidget.Manager.grid[this.config.itemId] = this;
        return this.config.grid;
    };
}
/**
 * 表格创建方法
 */
DSYGrid.createGrid = function (config) {
    return new DSYGridV2().create(config);
};
/**
 * 创建获取表格方法
 */
DSYGrid.getGrid = function (itemId) {
    return Ext.ComponentQuery.query('grid#' + itemId)[0];
};
/**
 * 创建获取导出按钮方法
 */
DSYGrid.getBtnExport = function (itemId) {
    return DSYWidget.Manager.grid[itemId].config.exportExcel.btn;
};
/**
 * 导出按钮点击事件
 */
DSYGrid.exportExcelClick = function (itemId, config, successCallback, failCallBack) {
    var config_grid = DSYWidget.Manager.grid[itemId].config;
    config_grid.exportExcel = $.extend(true, {}, config_grid.exportExcel, config);
    var exportExcel = config_grid.exportExcel;
    // 如果导出功能为true,并且导出按钮存在
    if (exportExcel.exportExcel) {
        //当beforeclick事件存在时，先执行beforeclick
        if (typeof exportExcel.listeners.beforeclick != 'undefined' && exportExcel.listeners.beforeclick && typeof(exportExcel.listeners.beforeclick) == "function") {
            var result = exportExcel.listeners.beforeclick(config_grid);
            if (!result) {
                return false;
            }
        }
        exportExcel = DSYGrid.exportExcelConfig(itemId, config_grid);
        var param = $.extend(exportExcel.param, DSYGrid.getGrid(itemId).getStore().getProxy().extraParams);
        //删除每一列中的renderer和editor,防止json转string出错
        for (var i in exportExcel.config.headerJson) {
            var header = exportExcel.config.headerJson[i];
            delete header.editor;
            delete header.renderer;
            if (param.deep > 1) {
                for (var j in header.columns) {
                    var header_child = header.columns[j];
                    delete header_child.editor;
                    delete header_child.renderer;
                }
            }
        }
        param.config = encode64(Ext.JSON.encode(exportExcel.config));
        //导出Excel：使用虚拟表单提交
        if (!$('form#download') || $('form#download').length <= 0) {
            $('<form id="download"></form> ').appendTo(document.body);
        }
      
        // var frm = document.createElement('form');chrome有效,IE无效
        // Ext.Ajax.request({
        //     url: exportExcel.url,
        //     isUpload: true,
        //     form: 'download',
        //     params: param,
        //     success: successCallback,
        //     failure: failCallBack
        // });
        //将param中值为null的处理为空字符串
        for (var i in param) {
            if (param[i] == null) {
                param[i] = "";
            }
        }
        downloadPublicFiles(exportExcel.url,'POST',param).then(function(data){
            if(successCallback){
                successCallback(data)
            }
        }).catch(function(error){
            if(failCallBack){
                failCallBack(error)
            }
        })
        
    }
};
/**
 * 导出按钮配置
 */
DSYGrid.exportExcelConfig = function (itemId, gridConfig) {
    // 如果导出功能为true
    if (gridConfig.exportExcel.exportExcel) {
    	var columns = [];
    	if(gridConfig.enableLocking || gridConfig.grid.lockedGrid){
    		var lockedColumns = gridConfig.grid.lockedGrid.getColumns();
    		var normalColumns = gridConfig.grid.normalGrid.getColumns();
    		for(var i in lockedColumns){
    			columns.push(lockedColumns[i]);
    		}
    		for(var i in normalColumns){
    			columns.push(normalColumns[i]);
    		}
    	}else{
    		//获取表格各列对象
    		columns = gridConfig.grid.getColumns();
    	}        
        var colWidth = {};
        var columnsNum = 0;//表头实际列数;
        for (var i = 0; i < columns.length; i++) {
            if (columns[i].hidden) {
                //continue;
            }
            //判断是否是checkbox列
            if (typeof columns[i].initialCls != 'undefined' && columns[i].initialCls.trim().endWith("checkbox")) {
                continue;
            }
            columnsNum++;
            if (columns[i].xtype == 'rownumberer' && columns[i].dataIndex == '') {
                columns[i].dataIndex = 'rownumberer';
            }
            colWidth[columns[i].dataIndex] = columns[i].getCellWidth();
        }
        //获取表头总行数与总列数
        var deep = 1;//表头实际行数;
        if (gridConfig.exportExcel.param.deep) {
            deep = gridConfig.exportExcel.param.deep;//表头实际行数;
        }
        gridConfig.exportExcel.param.columnsNum = columnsNum;
        gridConfig.exportExcel.param.deep = deep;
        //循环获取各列宽度与样式
        var colArray = gridConfig.headerConfig.headerJson;
        /**
         * 递归循环初始化各列
         * @param cols
         */
        this.setColumns = function (cols) {
            deep--;
            //如果为空返回
            if (cols == null || cols.length <= 0) {
                return;
            }
            for (var i = 0; i < cols.length; i++) {
                var column = cols[i];
                if (column.hidden) {
                    //continue;
                }
                //取得列对应宽度
                column.width = colWidth[column.dataIndex];
                // 取得列合并列数
                if (!column.colspan) {
                    if (column.columns && column.columns.length > 0) {
                        column.colspan = column.columns.length;
                    } else {
                        column.colspan = 1;
                    }
                }
                //取得行合并行数
                if (!column.rowspan) {
                    if (column.columns && column.columns.length > 0) {
                        column.rowspan = 1;
                    } else {
                        column.rowspan = deep;
                    }
                }
                //列css，增加默认样式,去除重复后转换为对象
                if (typeof(column.css) != "undefined" && column.css != null && column.css != "") {
                    //将表头css转换为对象
                    var cssStr = gridConfig.headerConfig.headerCss + column.css;
                    var colCssArray = cssStr.split(";");
                    var colCss = {};
                    for (var j in colCssArray) {
                        var name = colCssArray[j].split(":")[0];
                        if (typeof(name) == "undefined") {
                            continue;
                        }
                        var value = colCssArray[j].split(":")[1];
                        if (typeof(value) == "undefined") {
                            continue;
                        }
                        colCss[name] = value;
                    }
                    column.css = colCss;
                }
                if (column.columns && column.columns.length > 0) {
                    deep = this.setColumns(column.columns);
                    deep++;
                }
            }
            return deep;
        };
        deep++;
        this.setColumns(colArray);
        //将表头默认css转换为对象
        var cssStr = gridConfig.headerConfig.headerCss;
        var colCssArray = cssStr.split(";");
        var colCss = {};
        for (var j in colCssArray) {
            var name = colCssArray[j].split(":")[0];
            if (typeof(name) == "undefined") {
                continue;
            }
            var value = colCssArray[j].split(":")[1];
            if (typeof(value) == "undefined") {
                continue;
            }
            if(name == "background-color"){
                var colorTemp = $(".x-column-header").css("background-color");
                if (!isNull(colorTemp)){
                    value = colorRGB2Hex(colorTemp);
                }
            }
            colCss[name] = value;
        }
        //配置JSON
        gridConfig.exportExcel.config = {
            headerJson: colArray,//表头配置json
            headerCss: colCss//表头默认样式
        };
    }
    return gridConfig.exportExcel;
};
/**
 * 创建获取分页按钮方法
 */
DSYGrid.getBtnPage = function (itemId) {
    return DSYWidget.Manager.grid[itemId].getPageConfig().pageToolBar;
};
/**
 * 从DSYGrid管理器中销毁DSYGrid
 * @param itemId
 */
DSYGrid.destoryGrid = function (itemId) {
    if (typeof(DSYGrid.getGrid(itemId)) == "undefined" || DSYGrid.getGrid(itemId) == null) {
        return;
    }
    DSYGrid.getGrid(itemId).close();
    delete DSYWidget.Manager.grid[itemId];
};
/**
 * ext扩展插件：扩展分页按钮组件：每页显示记录数插件
 */
DSYGrid.component.PagingToolbar = Ext.extend(Ext.toolbar.Paging, {
    init: function (pagingToolbar) {
        this.pagingToolbar = pagingToolbar;
        //根据每页显示记录数的样式，显示下拉框还是数字匡
        if (this.pageConfig.pageNum && this.pageConfig.pageNumStyle == 'combo') {
            this.inputItem = [
                '每页',
                Ext.create('Ext.form.ComboBox', {
                    width: this.pageConfig.pageNumWidth,
                    value: this.pageConfig.pageSize,
                    margin: '0 0 0 -10',
                    allowBlank: false,
                    editable:false,
                    blankText: '每页显示记录数不允许为空',
                    store: [10, 20, 50, 100, 200],
                    listeners: {
                        scope: this,
                        change: this.onPagingChange
                    }
                }),
                '条'];
        } else if (this.pageConfig.pageNum && this.pageConfig.pageNumStyle == 'numberfield') {
            this.inputItem = [
                '每页',
                Ext.create('Ext.form.field.Number', {
                    width: this.pageConfig.pageNumWidth,
                    value: this.pageConfig.pageSize,
                    margin: '0 0 0 -10',
                    allowDecimals: false,
                    allowNegative: false,
                    enableKeyEvents: true,
                    //maxValue: 999,
                    //maxText: '每页不允许超过999条',
                    selectOnFocus: true,
                    submitValue: false,
                    listeners: {
                        scope: this,
                        blur: this.onPagingChange
                    }
                }),
                '条'];
        }
        //将插件插入到分页组件指定位置
        pagingToolbar.insert(this.pageConfig.pageNumIndex, this.inputItem);
    },
    onPagingChange: function (field) {
        //监听事件，刷新表格
        if (field.isValid()) {
            var pageSize = field.getValue();
            if (typeof(pageSize) != 'number') {
                pageSize = Number(pageSize);
                if (isNaN(pageSize)) {
                    Ext.Msg.alert('提示', '每页显示数据数只能是数字类型');
                    return;
                }
            }
            this.pageSize = pageSize;
            this.pageConfig.pageSize = this.pageSize;
            this.pagingToolbar.store.setPageSize(this.pageSize);
            this.pagingToolbar.store.currentPage = 1;//设置当前页码为1
            this.pagingToolbar.doRefresh();
        }
    }
});
/**
 * ext扩展插件：表单多选下拉框（带checkbox）
 */
Ext.define('Ext.ux.MultiComboBox', {
    extend: 'Ext.form.ComboBox',
    alias: 'widget.multicombobox',
    initComponent: function () {
        this.multiSelect = true;//设置combobox的多选项为true
        this.editable = false;
        this.listConfig = {
            itemTpl: Ext.create('Ext.XTemplate', '<input type="checkbox">{' + this.displayField + '}'),//为	选项添加checkbox
            //解决问题：选中之后， 下一次点击下拉单的话，会更新 combobox 的下拉选项(combobox), 之前选中的check box 会被取消选择。
            onItemSelect: function (record) {
                var node = this.getNode(record);
                if (node) {
                    Ext.fly(node).addCls(this.selectedItemCls);

                    var checkboxs = node.getElementsByTagName("input");
                    if (checkboxs != null) {
                        var checkbox = checkboxs[0];
                        checkbox.checked = true;
                    }
                }
            },
            listeners: {
                //监听事件：选项选中或取消时，操作对应checkbox
                itemclick: function (view, record, item) {
                    var isSelected = view.isSelected(item);
                    var checkboxs = item.getElementsByTagName("input");
                    if (checkboxs != null) {
                        var checkbox = checkboxs[0];
                        checkbox.checked = !isSelected;
                    }
                }
            }
        };
        this.callParent();
    }
});
/**
 * 扩展store插入数据方法
 */
Ext.override(Ext.data.Store, {
    insertData: function (index, records) {
        var me = this;
        if (typeof index == 'undefined' || index == null) {
            index = me.getCount();
        }
        if (me.getCount() > 0) {
            me.insert(index, records);
        } else {
            me.loadData(Ext.isArray(records) ? records : [records]);
        }
    }
});
//每一个列都会出现鼠标悬浮上去显示内容
/**
 * //适用于Extjs4.x
 * @class Ext.grid.GridView
 * @override Ext.grid.GridView
 * GridPanel单元格不能选中复制问题
 * 单元格数据显示不完整 ,增加title 浮动提示信息
 */
Ext.override(Ext.grid.GridPanel, {
    afterRender: Ext.Function.createSequence(Ext.grid.GridPanel.prototype.afterRender, function () {
        // 默认显示提示
        if (!this.cellTip) {
            return;
        }
        var view = this.getView();
        this.tip = new Ext.ToolTip({
            target: view.el,
            delegate: '.x-grid-cell-inner',
            trackMouse: true,
            renderTo: document.body,
            ancor: 'top',
            style: 'background-color: #FFFFCC;',
            dismissDelay:600000,//tips提示添加时间控制，显示10分钟
            listeners: {
                beforeshow: function updateTipBody(tip) {
                    //取cell的值
                    //fireFox  tip.triggerElement.textContent
                    //IE  tip.triggerElement.innerText
                    var tipText = (tip.triggerElement.innerText || tip.triggerElement.textContent);
                    if (Ext.isEmpty(tipText) || Ext.isEmpty(tipText.trim())) {
                        return false;
                    }

                    tip.update(tipText);
                }
            }
        });
    }),
    lock: function(g, l, e) {
        var i = this,
        h = i.normalGrid,
        c = i.lockedGrid,
        hColumns = h.getColumns(),
        d = h.view,
        m = c.view,
        k = h.headerCt,
        j, a, b;
        g = g || k.getMenu().activeHeader;
        b = g.hasFocus;
        e = e || c.headerCt;
        a = g.ownerCt;
        if (!g.isLockable()) {
            return
        }
        if (g.flex) {
            g.width = g.getWidth();
            g.flex = null
        }
        Ext.suspendLayouts();
        if (c.hidden) {
            c.show()
        }
        d.blockRefresh = m.blockRefresh = true;
        for(var n in hColumns){
        	a.remove(hColumns[n], false);
        	hColumns[n].locked = true;
            if (Ext.isDefined(l)) {
                e.insert(l, hColumns[n])
            } else {
                e.add(hColumns[n])
            }
            if(g.dataIndex == hColumns[n].dataIndex){
            	break;
            }
        }
        d.blockRefresh = m.blockRefresh = false;
        j = i.syncLockedWidth();
        if (j[0]) {
            c.getView().refreshView()
        }
        if (j[1]) {
            h.getView().refreshView()
        }
        Ext.resumeLayouts(true);
        if (b) {
            g.focus()
        }
        i.fireEvent("lockcolumn", i, g)
    },
    unlock: function(e, k, d) {
        var h = this,
        g = h.normalGrid,
        b = h.lockedGrid,
        bColumns = b.getColumns(),
        p = bColumns.length,
        c = g.view,
        l = b.view,
        j = b.headerCt,
        i, a;
        if (!Ext.isDefined(k)) {
            k = 0
        }
        e = e || j.getMenu().activeHeader;
        a = e.hasFocus;
        d = d || g.headerCt;
        Ext.suspendLayouts();
        c.blockRefresh = l.blockRefresh = true;
        for(var n = 0;n<bColumns.length;n++){
//            if(e.dataIndex == bColumns[n].dataIndex){
//            	p = n;
//            }
//            if(n>=p){
        	   if(!bColumns[n].isCheckerHd && bColumns[n].dataIndex != 'rownumberer'){
        		   e.ownerCt.remove(bColumns[n], false);
                   e.locked = false;
                   d.insert(k, bColumns[n]);
                   k++;  
        	   }
//            }
        }
        c.blockRefresh = l.blockRefresh = false;
        i = h.syncLockedWidth();
        if (i[0]) {
            b.getView().refreshView()
        }
        if (i[1]) {
            g.getView().refreshView()
        }
        Ext.resumeLayouts(true);
        if (a) {
            e.focus()
        }
        h.fireEvent("unlockcolumn", h, e)
    },
    getPlugin: function(pluginId) {//根据锁定列重构获取依赖方法 如果有锁定列默认获取非锁定行依赖
        var i
            plugins = this.plugins;
        if(this.enableLocking){
        	plugins = this.normalGrid.plugins;
        }
        var ln = plugins && plugins.length;
        for (i = 0; i < ln; i++) {
            if (plugins[i].pluginId === pluginId) {
                return plugins[i];
            }
        }
        return null;
    },
    getLockPlugin: function(pluginId) {//根据锁定列增加锁定列获取依赖方法
        var i
            plugins = this.plugins;
        if(this.enableLocking){
        	plugins = this.lockedGrid.plugins;
        }
        var ln = plugins && plugins.length;
        for (i = 0; i < ln; i++) {
            if (plugins[i].pluginId === pluginId) {
                return plugins[i];
            }
        }
        return null;
    }
});

/**
 * 改变列宽或者改变列顺序时把改变后的列信息存储到本地
 */
DSYGrid.localStorage = function (self){
	var grid = self;
	var itemId = grid.getItemId();
	var menu = DSYGrid.getMenu();
    var newColumns = grid.getColumns();
    var saveJson = [];
    for( var i = 0; i < newColumns.length; i++){
         var newColumn = newColumns[i];
         var dataIndex = newColumn.dataIndex;
         var width = newColumn.width;
         var index = newColumn.fullColumnIndex;
         var hidden = newColumn.hidden;
         saveJson.push({
                    dataIndex:dataIndex,
                    width:width,
                    hidden:hidden,
                    header:newColumn.text
         });
    }
    if(window.localStorage){
        var storage = window.localStorage;
        var storageString = JSON.stringify(saveJson);
        storage.setItem(menu+itemId,storageString);
   }
};

/**
 * 当列更新后把改变后的列信息存储到本地
 */
DSYGrid.localStorageByColumns = function(selfColumns,itemId){
	var menu = DSYGrid.getMenu();
	var saveJson = [];
    for( var i = 0; i < selfColumns.length; i++){
         var newColumn = selfColumns[i];
         var dataIndex = newColumn.dataIndex;
         var width = newColumn.width;
         var index = newColumn.fullColumnIndex;
         var hidden = newColumn.hidden;
         // saveJson.push(newColumn)
         if(newColumn.locked){
        	 saveJson.push({
                 dataIndex:dataIndex,
                 width:width,
                 locked:newColumn.locked,
                 hidden:hidden,
                 header:newColumn.text
        	 });
         }else{
        	 saveJson.push({
                 dataIndex:dataIndex,
                 width:width,
                 hidden:hidden,
                 header:newColumn.text
        	 });
         }
    }
    if(window.localStorage){
        var storage = window.localStorage;
        var storageString = JSON.stringify(saveJson);
        storage.setItem(menu+itemId,storageString);
   }
};

/**
 * 删除本地存储
 */
DSYGrid.localStorageRemove = function(menu,itemId){
	 if(window.localStorage){
         var storage = window.localStorage;
         storage.removeItem(menu+itemId);
         //获取当前grid
         var grid=DSYGrid.getGrid(itemId);
         //获取当前grid管理器
         var newGrid = window.DSYWidget.Manager.grid[itemId];
         //初始化表格配置
         newGrid.loadProperty();
         //获取表头配置
         var newHeaderColumns = newGrid.config.columns;
         //重置表格
         grid.reconfigure(null,newHeaderColumns);
         Ext.resumeLayouts(true);  
    }
};

/**
 * 根据菜单+菜单编码+rownumberer 判断是否允许本级记忆
 */
DSYGrid.getLocalStorageFlag = function(selfColumns){
	var flag = true;
	var pathname = window.location.pathname;
	var menucode = getQueryParam('menucode');
	if(pathname == null || pathname == "" || menucode == null || menucode ==""){
		flag = false;
	}
	var rownumFlag = false;
	if(flag){
		for( var i = 0; i < selfColumns.length; i++){
	        var newColumn = selfColumns[i];
	        var xtype = newColumn.xtype;
	        if(xtype == "rownumberer"){
	        	rownumFlag = true;
	        }
	   }
	}
  return rownumFlag;
};

/**
 * 获取菜单和编码组合
 */
DSYGrid.getMenu = function(){
	var pathname = window.location.pathname;
	var menucode = getQueryParam('menucode');
	return pathname + menucode;
};


/**
 * 根据菜单+菜单编码+rownumberer 判断是否允许本级记忆
 */
DSYGrid.getLockFlag = function(selfColumns){
	var flag = false;
	for( var i = 0; i < selfColumns.length; i++){
        var newColumn = selfColumns[i];
        var xtype = newColumn.xtype;
        if(xtype == "rownumberer"){
        	flag = true;
        	break;
        }
   }	
  return flag;
};
